/*
 * Copyright (c) GoKeep by gokeep.org. 2022-2023. All rights reserved
 */
package org.gokeep.communication.event.impl;

import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.gokeep.common.document.Group;
import org.gokeep.common.document.GroupMember;
import org.gokeep.common.document.HistoryMessage;
import org.gokeep.common.dto.UserAioSession;
import org.gokeep.common.dto.UserClientSessionAttr;
import org.gokeep.common.exception.GoKeepException;
import org.gokeep.common.repository.GroupRepository;
import org.gokeep.communication.component.HistoryMessageComponent;
import org.gokeep.communication.event.Event;
import org.gokeep.communication.proto.CommandProto;
import org.gokeep.communication.proto.MessageProto;
import org.smartboot.socket.transport.AioSession;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Optional;

@Slf4j
@Component
public class ChatEvent extends Event {

    @Resource
    private GroupRepository groupRepository;

    @Resource
    private HistoryMessageComponent historyMessageComponent;

    @Override
    @SneakyThrows
    public void process(AioSession session, MessageProto.Message message) {
        // 解析聊天消息数据
        HistoryMessage historyMessage = historyMessageComponent.generateHistoryMessage(message);
        // 如果是群组消息， 则发送给群组的每一个人, 点对点的单独发送
        if (historyMessage.isGroupMessage()) {
            String groupId = historyMessage.getGroupId();
            Optional<Group> groupOptional = groupRepository.findById(groupId);
            assert groupOptional.isPresent() : new GoKeepException("用户群组不存在");
            Group group = groupOptional.get();
            List<GroupMember> members = group.getGroupMembers();
            List<String> userIds = members.stream()
                    .map(GroupMember::getUserId)
                    .filter(userId -> !userId.equals(historyMessage.getFrom()))
                    .toList();
            List<UserAioSession> userAioSessions = sessionCacheComponent.getAllLocalSessionByUserId(userIds);
            write(userAioSessions, message);
        } else {
            List<UserAioSession> userAioSessions = sessionCacheComponent.getAllLocalSessionByUserId(historyMessage.getTo());
            write(userAioSessions, message);
        }
        historyMessageComponent.create(historyMessage);
    }

    @Override
    protected CommandProto.CommandEnum getEventType() {
        return CommandProto.CommandEnum.CHAT_REQUEST;
    }
}